package com.usian.security.controller;

import com.usian.common.model.Result;
import com.usian.common.utils.JwtUtil;
import com.usian.security.entity.LoginUser;
import com.usian.security.entity.User;
import com.usian.security.exception.CustomException;
import com.usian.security.service.UserService;
import com.usian.security.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: UserController
 * Author:   WGG
 * Date:    2022-12-2022/12/21-16:41
 * Version: 1.0
 * Description:
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/login")
    public Result<Map<String,String>> login(@RequestBody User query){
        //使用AuthenticationManager的认证接口进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(query.getUserName(),query.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (authenticate ==null){
            throw new CustomException("登录失败");
        }
        //认证成功则通过jwt创建token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String token = JwtUtil.createToken(loginUser.getUser().getUserId(), loginUser.getUser().getUserName());
        Map<String,String> data = new HashMap<>();
        data.put("token",token);

        //把用户信息存入到redis
        String key = "login:"+ loginUser.getUser().getUserId();
        if (redisUtil.containsKey(key)){
            redisUtil.del(key);
        }
        redisUtil.set(key,loginUser);

        return Result.createSuccess(data);
    }

    @GetMapping(value = "/hello")
    @PreAuthorize("hasAuthority('sys:admin')")
    public String sayHello(){
        return "hello world";
    }


}
